package com.oocl.daobooks.datagen;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;

import com.oocl.daobooks.pojo.Book;

public class BookFileHandler {

	public static void writeToFile(String filename) {
		ObjectOutputStream out = null;
		List<Book> bookList = BookGenerator.getRandomBooks(10000);
		try {
			out = new ObjectOutputStream(new FileOutputStream(filename));
			out.writeObject(bookList);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	@SuppressWarnings("unchecked")
	public static List<Book> readFromFile(String filename) {
		ObjectInputStream in = null;
		List<Book> bookList = null;
		try {
			in = new ObjectInputStream(new FileInputStream(filename));
			bookList = (List<Book>) in.readObject();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return bookList;
	}
}
